#memeber/member_wechat.py
import requests
import secrets
from datetime import datetime, timedelta
from flask import session, flash, redirect, url_for, current_app
from inc.models import db, WechatConfig, AdminMember, User

class WechatAuth:
    @staticmethod
    def get_access_token(config):
        """获取企微访问令牌"""
        token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={config.corp_id}&corpsecret={config.corp_secret}"
        try:
            response = requests.get(token_url, timeout=10)
            response.raise_for_status()  # 如果请求失败则抛出HTTPError
            data = response.json()
            if data.get('errcode') != 0:
                current_app.logger.error(f"获取访问令牌失败: {data.get('errmsg')}")
                return None
            return data['access_token']
        except requests.exceptions.RequestException as e:
            current_app.logger.exception(f"获取企微访问令牌异常: {e}")
            return None
        except ValueError: # requests.JSONDecodeError in newer versions
            current_app.logger.exception("解析企微访问令牌响应JSON失败")
            return None

    @staticmethod
    def get_user_info(access_token, code):
        """获取企微用户信息"""
        userinfo_url = f"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={access_token}&code={code}"
        try:
            response = requests.get(userinfo_url, timeout=10)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            current_app.logger.exception(f"获取企微用户信息异常: {e}")
            return None
        except ValueError: # requests.JSONDecodeError in newer versions
            current_app.logger.exception("解析企微用户信息响应JSON失败")
            return None

    @staticmethod
    def handle_login_callback(state, code, config, is_admin=False):
        """处理扫码登录回调"""
        # 验证state参数
        if state != session.pop('wechat_login_state', None):
            flash('登录状态验证失败或已过期', 'danger')
            return None

        # 获取访问令牌
        access_token = WechatAuth.get_access_token(config)
        if not access_token:
            flash('获取访问令牌失败', 'danger')
            return None

        # 获取用户信息
        userinfo = WechatAuth.get_user_info(access_token, code)
        if not userinfo or userinfo.get('errcode') != 0:
            flash(f'获取用户信息失败: {userinfo.get("errmsg") if userinfo else "未知错误"}', 'danger')
            return None

        user_id = userinfo.get('UserId')
        if not user_id:
            flash('未获取到用户ID', 'danger')
            return None

        # 查找用户
        if is_admin:
            user = User.query.filter_by(wecom_userid=user_id).first()
            if not user:
                flash('未找到对应用户', 'danger')
                return None
            admin_member = AdminMember.query.filter_by(wecom_userid=user_id).first()
            if not admin_member or not admin_member.admin_user:
                flash('用户未关联管理员账号', 'danger')
                return None
            return admin_member.admin_user
        else:
            member = AdminMember.query.filter_by(wecom_userid=user_id).first()
            if not member:
                # 自动创建新用户
                member = AdminMember(
                    name=f"企微用户_{user_id[:8]}",
                    wecom_userid=user_id,
                    status=True,
                    create_time=datetime.now()
                )
                # 生成并设置一个安全的随机密码
                random_password = secrets.token_hex(8)
                member.set_password(random_password) # 假设存在 set_password 方法
                db.session.add(member)
                db.session.commit()
                flash(f'已为您自动创建账号，初始密码为：{random_password}，请登录后立即修改密码。', 'success')
            return member